var app = angular.module('conversionTool', [ 'ui.bootstrap' ]);

app.controller('formularCtrl', [ '$scope', '$http', function($scope, $http) {

	$scope.defaultColumnName = "column name";

	$scope.defaultOperation = "operation";

	$scope.columnName = $scope.defaultColumnName;

	$scope.operation = $scope.defaultOperation;

	$scope.dataTemplateId = 1;

	$scope.setDataTemplateId = function(id) {

		$scope.formula = new Object();
		$scope.formula["dataTemplateId"] = $scope.dataTemplateId = id;

		$http.post('/rest/dataAdaptor/getFormula', $scope.formula).success(function(data) {

			$scope.formula = data;

			if ($scope.formula == "" || $scope.formula == undefined) {
				$scope.formula = new Object();
			}

			if ($scope.formula.formula == undefined) {
				$scope.formula.formula = new Array();
			}

		}).error(function(data) {
			console.log(data);
			$scope.formula = new Object();
			$scope.formula.formula = new Array();
		});

	}
	
	$scope.back=function(){
		
		window.history.back();
	}
	
	

	$scope.setOperation = function(op, number) {
		$scope.operation = op;
		$scope.parameterNumber = number;
	}

	$scope.setColumnName = function(col) {
		$scope.columnName = col;
	}

	$scope.addCondition = function() {

		if ($scope.columnName == $scope.defaultColumnName) {
			$scope.msg = "Please choose a column";
		} else if ($scope.operation == $scope.defaultOperation) {
			$scope.msg = "Please choose an operation";
		} else if ($scope.parameterNumber == 1 && ($scope.value1 == undefined || $scope.value1 == "") ) {
			$scope.msg = "Please enter a value to Parameter1 for this operation ";
		} else if ($scope.parameterNumber == 2 && ($scope.value1 == undefined || $scope.value1 == "" || $scope.value2 == undefined || $scope.value2 == "") ) {
			$scope.msg = "Please enter values to Parameter1 and Parameter2 for this operation ";
		}else {
			var result = new Object();

			result.columnName = $scope.columnName;
			result.operation = $scope.operation;
			if ($scope.value1 != undefined) {
				result.value1 = $scope.value1;
			}

			if ($scope.value2 != undefined)
				result.value2 = $scope.value2;

			$scope.formula.formula.push(result);

			$scope.value1 = "";
			$scope.value2 = "";

			$scope.columnName = $scope.defaultColumnName;

			$scope.operation = $scope.defaultOperation;
			$scope.msg = "";

		}
	}

	$scope.deleteFilter = function(id) {
		$scope.formula.formula.splice(id, 1);
	}

	$scope.save = function() {

		$scope.formula["dataTemplateId"] = $scope.dataTemplateId;

		$http.post('/rest/dataAdaptor/saveFormula', $scope.formula).success(function(data) {

			if (data) {
				$scope.msg = "save data success";
			} else {
				$scope.msg = "sever error, please refresh page.";
			}

		}).error(function(data) {
			console.log(data);
			$scope.msg = "sever error, please refresh page.";
		});
	}

} ]);
